package global

import (
	"sync"

	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"gopkg.in/natefinch/lumberjack.v2"
)

var LOG *zap.SugaredLogger

func initZap(wg *sync.WaitGroup) {
	defer wg.Done()

	writeSyncer := getLogWriter()

	encoder := getEncoder()

	core := zapcore.NewCore(encoder, writeSyncer, zapcore.Level(CONFIG.Zap.Level))

	logger := zap.New(core, zap.AddCaller())

	defer logger.Sync() // flushes buffer, if any

	LOG = logger.Sugar()
}

// 编码器(如何写入日志)
func getEncoder() zapcore.Encoder {

	encoderConfig := zap.NewProductionEncoderConfig()

	encoderConfig.EncodeTime = zapcore.TimeEncoderOfLayout("2006-01-02 15:04:05") // 转义时间戳

	encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder // 大写字母表示

	return zapcore.NewConsoleEncoder(encoderConfig)
}

// 日志分割(大小等信息)
func getLogWriter() zapcore.WriteSyncer {

	lumberJackLogger := &lumberjack.Logger{
		Filename:   CONFIG.Zap.Filename,
		MaxSize:    CONFIG.Zap.MaxSize,    // 最大1M
		MaxBackups: CONFIG.Zap.MaxBackups, // 最多5个备份
		MaxAge:     CONFIG.Zap.MaxAge,     // 保存30天
		Compress:   CONFIG.Zap.Compress,
	}

	return zapcore.AddSync(lumberJackLogger)
}
